package com.flute.icrawler.app.util;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class TextUtil {

	/**
	 * 从文件内容中获取字符编码
	 * 
	 * @param strContent
	 * @return
	 */
	public static String findCharset(String strContent) {
		String charset = "utf-8";
		Pattern pattern = Pattern.compile("charset=([^'\"]+)");

		Matcher matcher = pattern.matcher(strContent);
		if (matcher.find()) {
			charset = matcher.group(1);

		}
		return charset;
	}

	/**
	 * 将Unicode码换成字符
	 * 
	 * @param unicodeStr
	 * @return
	 */
	public static String native2ascii(String unicodeStr) {
		char[] in = unicodeStr.toCharArray();
		char[] out = new char[unicodeStr.length() * 2];
		int outLen = 0;
		int off = 0;
		int end = off + unicodeStr.length();
		int aChar;
		while (off < end) {
			aChar = in[off++];
			if (aChar == '\\') {
				aChar = in[off++];
				if (aChar == 'u') {
					int value = 0;
					for (int i = 0; i < 4; i++) {
						aChar = in[off++];
						if (aChar >= '0' && aChar <= '9') { // 0-9
							value = (value << 4) + aChar - '0';
							continue;
						} else if (aChar >= 'A' && aChar <= 'Z') { // A-Z
							value = (value << 4) + 10 + aChar - 'A';
							continue;
						} else if (aChar >= 'a' && aChar <= 'z') { // a-z
							value = (value << 4) + 10 + aChar - 'a';
							continue;
						} else {
							throw new IllegalArgumentException(
									"Malformed  \\uxxxx encoding.");
						}
					}
					out[outLen++] = (char) value;
				} else {
					out[outLen++] = '\\';
					out[outLen++] = (char) aChar;
				}
			} else {
				out[outLen++] = (char) aChar;
			}
		}
		return new String(out, 0, outLen);
	}

	public boolean isExpectedType(String contentType, String[] expectedPrefixs) {

		for (int i = 0; i < expectedPrefixs.length; i++) {

			if (isExpectedType(contentType, expectedPrefixs[i])) {
				return true;
			}
		}
		return false;
	}

	public boolean isExpectedType(String contentType, String expectedPrefix) {

		return contentType != null
				&& contentType.toLowerCase().startsWith(expectedPrefix);
	}
}
